package com.sharding.service;

import com.sharding.entity.Order;
import com.sharding.repository.OrderRepository;
import io.shardingsphere.core.api.HintManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by dongjigong on 2018/6/6.
 *
 * @Email osbornjonny@126.com
 * @Description
 */
@Service
public class DemoServiceImpl implements DemoService {

    @Autowired
    private DataSource dataSource;

    @Override
    public List<Object> queryOrders() {
        String sql = "SELECT * FROM t_order";
        try (
                HintManager hintManager = HintManager.getInstance();
                Connection conn = dataSource.getConnection();
                PreparedStatement preparedStatement = conn.prepareStatement(sql)) {


            hintManager.addDatabaseShardingValue("t_order", "user_id", 1);
            hintManager.addTableShardingValue("t_order", "order_id", 2);
            try (ResultSet rs = preparedStatement.executeQuery()) {
                while (rs.next()) {

                }
            }
        } catch (SQLException e) {

        }
        return null;
    }

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
//    @Transactional
    public void createOrder() {
        jdbcTemplate.update("insert into t_order (user_id,order_id) values( 3,4) ");
        jdbcTemplate.update("insert into t_order (user_id,order_id) values( 4,5) ");
        jdbcTemplate.update("insert into t_order_item (user_name,member_id,password) values('zhangsan',21,'123456')");
//        Order order = new Order();
//        order.setUserId(1L);
//        orderRepository.saveAndFlush(order);
//        Order order2 = new Order();
//        order2.setUserId(2L);
//        orderRepository.saveAndFlush(order2);
    }

    @Override
    public void spileTeacher() {

    }


}